package com.example.administrator.k3xiangmu.fragment;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.example.administrator.k3xiangmu.Event;
import com.example.administrator.k3xiangmu.MainActivity;
import com.example.administrator.k3xiangmu.R;
import com.example.administrator.k3xiangmu.adapter.ShengchanAdapter;
import com.example.administrator.k3xiangmu.entity.ShengchangrenwudanEntity;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2017-01-05.
 */
public class DaikaigongFragment extends android.support.v4.app.Fragment {
    private ListView lv;
    private ShengchanAdapter adapter;
    private List<ShengchangrenwudanEntity> list = new ArrayList<>();
    private List<ShengchangrenwudanEntity> listcopy = new ArrayList<>();
      private ProgressDialog dialog;
    int a = 0;
    int b = 0;
    int c = 0;
    private String data = "";
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            list.clear();
            list.addAll(listcopy);

            adapter.notifyDataSetChanged();
            dialog.dismiss();
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Log.i("aaa","$$$$$$$$$$$$$$$$$$$$$$$$");
        View v = inflater.inflate(R.layout.fragment_daikaigong, container, false);
        adapter = new ShengchanAdapter(list, getActivity());
        lv = (ListView) v.findViewById(R.id.listview);
        lv.setAdapter(adapter);
            dialog = new ProgressDialog(getActivity());

        return v;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
        Log.i("aaa", "resume");

    }

    private void getData() {
        //  dialog = new ProgressDialog(getActivity());
          dialog.show();
        UpdateTextTask2 updateTextTask = new UpdateTextTask2(getActivity());
        updateTextTask.execute();
    }

    class UpdateTextTask2 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask2(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + MainActivity.ip + ";DatabaseName=" + MainActivity.userDB + "",
                        MainActivity.userName, MainActivity.userPwd);
                testConnection2(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            //  dialog.dismiss();
            // adapter=new ShengchanAdapter(list,getActivity());
            // lv.setAdapter(adapter);
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    adapter.notifyDataSetChanged();
//                }
//            },1000);
            handler.sendEmptyMessageDelayed(1, 200);


        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection2(Connection con) throws java.sql.SQLException {

        try {
            a = 0;
            b = 0;
            c = 0;
            listcopy.clear();
            String sql = "select b1.FModel, b1.FName,a1.FStartDate,a1.FPlanCommitDate,a1.FBillNo,a1.FAuxQty ,a1.FStatus,a1.FInterID from ICMO a1 inner join t_ICItem b1 on a1.FItemID=b1.FItemID";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor


            while (rs.next()) {// <code>ResultSet</code>最初指向第一行


                ShengchangrenwudanEntity entity = new ShengchangrenwudanEntity();
                entity.setFBillNo(rs.getString("FBillNo"));
                entity.setFAuxQty(rs.getInt("FAuxQty"));
                entity.setFModel(rs.getString("FModel"));
                entity.setFName(rs.getString("FName"));
                entity.setFPlanCommitDate(rs.getString("FPlanCommitDate"));
                entity.setFStartDate(rs.getString("FStartDate"));
                entity.setFStatus(rs.getInt("FStatus"));
                entity.setFInterID(rs.getInt("FInterID"));
                switch (rs.getInt("FStatus")) {
                    case 1:
                        a++;
                        break;
                    case 2:
                        b++;
                        break;
                    case 3:
                        c++;
                        break;

                }
                if (rs.getInt("FStatus") == 1) {
                    listcopy.add(entity);
                }

            }

            Event e = new Event();


            e.setA(a);
            e.setB(b);
            e.setC(c);

            EventBus.getDefault().post(e);


            rs.close();
            stmt.close();
        } catch (SQLException e) {

            System.out.println(e.getMessage().toString() + "dddddddddddd")
            ;


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
}
